package com.woniuxy.untis;


import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.sql.SQLOutput;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/chat/{userId}",encoders = MessageEncoder.class,decoders = MessageDecoder.class)
public class ChatServer {
    private static Map<String,Session> sessionMap = new ConcurrentHashMap();
    @OnOpen
   public void connection(Session session,@PathParam("userId") String userId){
       System.out.println(userId+"客户端连接成功！");
       sessionMap.put(userId,session);
        System.out.println("当前在线人数为："+sessionMap.size()+"人");
   }
    //OnMessage修饰的方法是从客户端发来的消息执行
    @SneakyThrows
    @OnMessage
    public void handleMsg(ChatMessage msg)  {
        System.out.println(msg);
        Session session = sessionMap.get(msg.getToAccount());
        msg.setTiom(LocalDateTime.now());
        session.getBasicRemote().sendObject(msg);
        //下面是群发
//        for (Session session : sessionMaps.values()) {
//            session.getBasicRemote().sendText(msg);//给客户端发信息
//        }

    }
    @OnError
    public void handleError(Throwable t){
        t.printStackTrace();
        System.out.println("Error");
    }
    @OnClose
    public void close(){
        System.out.println("close");
    }
}
